import DatePicker from "components/antd-compatible/date-picker";
import React, { Component, PropTypes } from 'react'
import { Modal, Form, Button, Icon, Dropdown, Menu, message, Input, Row, Col, Alert,  Spin, Select } from 'antd'
import { connect } from 'react-redux'
import Selector from 'components/selector';
import { messages, queryCurrencyPrecision } from "share/common";
import queryService from "containers/pay/bank-query/query.service";
import moment from "moment";
import paymentService from "containers/pay/pay-workbench/pay-workbench.service";
import CheckModal from "containers/pay/template/check-modal";
import ExportModal from "components/template/export-modal/export-modal";
import ErrorModal from "containers/pay/template/error-modal";

const { Option } = Select;

class PayModal extends Component {

  state = {
    loading: false,
    formProps: {},
    exportLoading: false,
    storageKey: localStorage.getItem('EBANK_PAYMENT_PAY') || 'file',
    selectFlag: true,
    bankInfo: {},
    accountBalance: false,
    chequeNumberFlag: {},
    rate: '',
    reimbursementBatchOID: '',
    errorVisible: false,
    errorData: {},
    surplusLoading: false,
    surplus: null,
    continueParams: {},
    optionList: [],
    isPayCheck: false
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.visible === this.props.visible) {
      return -1;
    }
    if (!nextProps.visible) {
      this.props.form.resetFields();
      this.setState({
        storageKey: localStorage.getItem('EBANK_PAYMENT_PAY') || 'file',
        selectFlag: true,
        bankInfo: {},
        accountBalance: false,
        chequeNumberFlag: {},
        surplus: null
      });
      return -1
    } else {
      this.setState({
        bankInfo: nextProps.bankInfo ? nextProps.bankInfo : {},
        accountBalance: nextProps.bankInfo ? nextProps.bankInfo.bankPayInfo.status === 'Y' && nextProps.bankInfo.accountType !== 'ALIPAY_LOGON_ID' : false,
        selectFlag: !nextProps.bankInfo
      }, () => {
        this.handleFormProps(nextProps.radioValue);
        this.getExchangeRate(nextProps.record);
        this.getOption();
        nextProps.record && nextProps.record[0].paymentData && this.setFormValue(nextProps.record);
        nextProps.bankInfo && this.selectorRef.handleFocus();
      })
    }
  }

  handleFormProps = value => {
    const { exportLoading, storageKey } = this.state;
    const { onCancel } = this.props;
    let formProps = {};
    const menu = (
      <Menu onClick={this.handleOk} style={{ maxHeight:250, overflow:'auto', width: '145px' }}>
        <Menu.Item key={'file'}>{messages('finance-4.key184')/*导出报盘文件*/}</Menu.Item>
        <Menu.Item key={'detail'}>{messages('finance-4.key185')/*导出报盘明细*/}</Menu.Item>
      </Menu>
    );
    switch (value) {
      case 'ONLINE_PAYMENT':
        formProps = {
          title: messages('finance-4.key186')/*线上支付确认*/,
          okText: messages('finance-4.key187')/*确认支付*/,
          onOk: this.handleOk
        };
        break;
      case 'WAIT_CHECK':
        formProps = {
          title: messages('finance-4.key188')/*编辑付款信息*/,
          okText: messages('common.save')/*保存*/,
          onOk: this.handleOk
        };
        break;
      case 'OFFLINE_PAYMENT':
        formProps = {
          title: messages('finance-4.key189')/*线下支付确认*/,
          okText: messages('finance-4.key187')/*确认支付*/,
          onOk: this.handleOk
        };
        break;
      default:
        formProps = {
          title: messages('finance-4.key182')/*落地文件支付*/,
          footer: [
            <Button onClick={onCancel} style={{ marginRight: '10px' }}>{messages('common.cancel')/*取消*/}</Button>,
            <Dropdown.Button
              overlay={menu}
              type='primary'
              placement="bottomRight"
              onClick={this.handleOk}
              disabled={exportLoading}
              icon={<Icon type="down"/>}
            >
              <span>{storageKey === 'file' ? messages('finance-4.key184')/*导出报盘文件*/ : messages('finance-4.key185')/*导出报盘明细*/}</span>
            </Dropdown.Button>
          ]
        };
        break;
    }
    this.setState({ formProps });
  };

  getOption = () => {
    const { bankInfo } = this.state;
    if (Object.keys(bankInfo).length) {
      paymentService.getTemplateExport(bankInfo.companyBank.bankName).then(res => {
        this.setState({ optionList: res.data },() => this.props.form.setFieldsValue({
          templateId: res.data[0].id
        }));
      })
    }
  };

  setFormValue = record => {
    try{
      let { paymentData } = record[0];
      this.props.form.setFieldsValue({
        payCompanyBankNumber: {
          companyBank: {
            bankAccountName: paymentData.payCompanyBankName,
            bankAccountNumber: paymentData.payCompanyBankNumber
          },
          companyId: paymentData.realPayCompanyId
        },
        currency: paymentData.currency,
        exchangeRate: paymentData.exchangeRate,
        paymentTypeId: {
          description: paymentData.paymentDescription,
          paymentMethodId: paymentData.paymentTypeId,
          paymentMethodCode: paymentData.paymentTypeCode
        },
        remark: paymentData.remark
      });
      this.setState({
        chequeNumberFlag: {
          description: paymentData.paymentDescription,
          paymentMethodId: paymentData.paymentTypeId,
          paymentMethodCode: paymentData.paymentTypeCode
        },
        bankInfo: {
          companyBank: {
            bankAccountName: paymentData.payCompanyBankName,
            bankAccountNumber: paymentData.payCompanyBankNumber,
            authToken: paymentData.appAuthToken,
            accountUid: paymentData.accountUid
          },
          accountType: paymentData.draweeAccountType,
          companyId: paymentData.realPayCompanyId
        },
        selectFlag: false
      })
    } catch (e) {}
  };

  getExchangeRate = record => {
    const { setOfBookId, company } = this.props;
    queryService.getExchangeRate({
      currency: record[0].currency,
      currencyDate: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
      setOfBookId: setOfBookId || company.setOfBooksId
    }).then(res => {
      this.setState({ rate: res.data.rate })
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  handleOk = value => {
    const { storageKey, bankInfo, chequeNumberFlag } = this.state, { record, radioValue, onOk, mode } = this.props;
    let key = value.key || null;
    if(key && key !== storageKey) {
      localStorage.setItem('EBANK_PAYMENT_PAY', key);
      this.setState({storageKey: key});
    }
    let params = {};
    if (mode === 'Fail') {
      params.details = record;
    } else {
      if (radioValue !== 'WAIT_CHECK') {
        params.dataAmountMap = {};
        record.map(item => {
          params.dataAmountMap[item.id] = item.currentPayAmount;
        });
      } else {
        params.id = record[0].id;
      }
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.paymentMethodCategory = radioValue === 'WAIT_CHECK' ? 'ONLINE_PAYMENT' : radioValue;
        values.payCompanyBankName = bankInfo.companyBank.bankAccountName;
        values.payCompanyBankNumber = bankInfo.companyBank.bankAccountNumber;
        values.paymentDescription = values.paymentTypeId.description;
        values.paymentTypeId = values.paymentTypeId.paymentMethodId;
        values.payDate && (values.payDate = moment(values.payDate));
        values.realPayCompanyId = bankInfo.companyId;
        values.paymentTypeCode = chequeNumberFlag.paymentMethodCode;
        values.draweeAccountType = bankInfo.accountType;
        values.appAuthToken = bankInfo.companyBank.authToken;
        values.accountUid = bankInfo.companyBank.accountUid;
        params[mode === 'Fail' ? 'payDTO' : 'cashPayDTO'] = values;
        this.setState({ loading: true, continueParams: params, exportLoading: radioValue === 'EBANK_PAYMENT' }, () => this.handleFormProps(radioValue));
        if (radioValue === 'WAIT_CHECK') {
          paymentService.updateWaitCheck(params).then(() => {
            message.success(messages('finance-4.key172')/*修改成功*/);
            this.setState({ loading: false, continueParams: {} }, onOk);
          }).catch(e => {
            message.error(e.response.data.message);
            this.setState({ loading: false, continueParams: {} });
          });
          return -1;
        }
        bankInfo.bankPayInfo && bankInfo.bankPayInfo.vendor && (params.bankPayChannel =  bankInfo.bankPayInfo.vendor);
        paymentService[mode === 'Fail' ? 'checkReEBank' : 'checkEBank'](params).then(res => {
          if (res.data.isSuccess) {
            if (bankInfo.bankPayInfo && bankInfo.bankPayInfo.status === 'Y' && radioValue === 'ONLINE_PAYMENT') {
              params.isPayCheck = res.data.isPayCheck;
              const createOrder = orderParams => {
                paymentService[mode === 'Fail' ? 'createReOrder' : 'createOrder'](Object.assign(orderParams,{
                  orderRequestNo: res.data.orderRequestNo
                })).then(response => {
                  switch (response.data.batStatus) {
                    case '01':
                      message.error(response.data.message);
                      this.setState({ loading: false, continueParams: {} });
                      return;
                    case '02':
                      Modal.confirm({
                        title: messages('finance-4.key90')/*重复风险警告*/,
                        content: <div>
                          <div>{messages('finance-4.key91')/*本次支付存在重复支付请求风险（同一批次中同一收款人账户同一交易金额出现多次），是否继续支付？*/}</div>
                          <div style={{ color: 'red' }}>{messages('finance-4.key92')/*注：请勿直接关闭浏览器，否则将会导致数据错误*/}</div>
                        </div>,
                        onOk: () => this.handleContinuePay(response.data),
                        onCancel: () => this.handleCancelContinue(response.data),
                        cancelText: messages('finance-4.key93')/*取消支付*/
                      });
                      return;
                    case '03':
                      Modal.warning({
                        title: messages('finance-4.key94')/*下单部分成功*/,
                        content: messages('finance-4.key95')/*银企直联下单部分成功，存在部分数据校验失败，请在付款工作台-支付失败或退票页签中查看并重新发起支付。*/
                      });
                      return;
                    default:
                      message.success(messages('finance-4.key96')/*支付成功*/);
                      response.data.aliPayUrl && (window.open(response.data.aliPayUrl));
                      this.setState({ loading: false, continueParams: {} }, onOk);
                      return;
                  }
                })
              };
              if (bankInfo.accountType === 'ALIPAY_LOGON_ID') {
                createOrder(params);
              } else {
                let uKey = !params.isPayCheck ? this.props.checkBrowser(res.data.orderRequestNo) : {};
                if ( uKey ) {
                  let tempParams = Object.assign(params, Object.keys(uKey).length > 0 ? {
                    bankPayChannel: bankInfo.bankPayInfo.vendor,
                    data: {
                      requestSeqNo: res.data.orderRequestNo,
                      oper: uKey.certInfo.split('@')[1],
                      operSign: uKey.res
                    }
                  } : {});
                  createOrder(tempParams);
                } else {
                  this.setState({ loading: false, continueParams: {} })
                }
              }
            } else {
              paymentService[mode === 'Fail' ? 'rePay' : 'confirmPay'](params).then(res => {
                let temp = { loading: false, exportLoading: false, continueParams: {} };
                radioValue === 'EBANK_PAYMENT' && (temp.reimbursementBatchOID = res.data.reimbursementBatchOID);
                const { failNum, successNum } = res.data;
                message.success(messages('finance-4.key140',{arg1: successNum,arg2: failNum})/*成功{arg1}条，失败{arg2}条*/);
                this.setState(temp, () => {
                  radioValue === 'EBANK_PAYMENT' && this.export.setInitState();
                  this.handleFormProps(radioValue);
                  onOk()
                });
              }).catch(e => {
                this.setState({ loading: false, exportLoading: false, continueParams: {} }, () => this.handleFormProps(radioValue));
                message.error(e.response.data.message)
              })
            }
          } else {
            this.setState({ errorData: res.data, exportLoading: false, isPayCheck: res.data.isPayCheck },() => {
              this.handleFormProps(radioValue);
              this.setState({ errorVisible: true })
            });
          }
        }).catch(e => {
          this.setState({ loading: false, exportLoading: false, continueParams: {} }, () => this.handleFormProps(radioValue));
          message.error(e.response.data.message)
        });
      }
    })
  };

  handleContinuePay = data => {
    const { porderId, batchNo, orderRequestNo } = data, { onOk } = this.props;
    let uKey = this.props.checkBrowser(orderRequestNo);
    paymentService.continuePay({
      porderId,
      batchNo,
      data: {
        requestSeqNo: orderRequestNo,
        oper: uKey.certInfo.split('@')[1],
        operSign: uKey.res
      }
    }).then(() => {
      message.success(messages('finance-4.key96')/*支付成功*/);
      this.setState({ loading: false, continueParams: {} }, onOk);
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({ loading: false, continueParams: {} });
    });
  };

  handleCancelContinue = data => {
    const { batchNo } = data, { onOk } = this.props;
    paymentService.cancelContinuePay({ batchNo }).then(() => {
      this.setState({ loading: false, continueParams: {} }, onOk);
    }).catch(e => {
      this.setState({ loading: false, continueParams: {} }, onOk);
      message.error(e.response.data.message);
    })
  };

  handleBanKChange = value => {
    this.setState({
      selectFlag: false,
      bankInfo: value,
      accountBalance: value.bankPayInfo ? value.bankPayInfo.status === 'Y' && value.accountType !== 'ALIPAY_LOGON_ID' : false,
      surplus: null
    }, this.getOption);
    this.props.form.setFieldsValue({ paymentTypeId: undefined });
  };

  handleChangeType = value => {
    this.setState({ chequeNumberFlag: value || {} });
  };

  handleCloseError = value => {
    const { onCancel, onOk } = this.props;
    this.setState({ errorVisible: false, loading: false, continueParams: {} }, value ? onOk : onCancel);
  };

  getSurplus = () => {
    const { bankInfo } = this.state;
    this.setState({ surplusLoading: true });
    queryService.queryAccountBalance([{
      id: bankInfo.id,
      acctNo: bankInfo.companyBank.bankAccountNumber,
      acctName: bankInfo.companyBank.bankAccountName,
      channel: bankInfo.bankPayInfo.vendor
    }]).then(res => {
      let surplus = res.data.find(item => item.id === bankInfo.id).accountBalance;
      this.setState({ surplusLoading: false, surplus });
    }).catch(e => {
      this.setState({ surplusLoading: false });
      message.error(e.response.data.message);
    })
  };

  render() {
    const { visible, onCancel, form, loginUser, record, companyId, radioValue, mode, companyCombinedPayment } = this.props;
    const { getFieldDecorator, getFieldValue } = form;
    const { loading, formProps, accountBalance, bankInfo, selectFlag, chequeNumberFlag, rate,
      storageKey, reimbursementBatchOID, errorVisible, errorData, surplus, surplusLoading, continueParams, optionList, isPayCheck } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14, offset: 1 },
    };
    return (
      <Modal
        visible={visible}
        confirmLoading={loading}
        bodyStyle={{maxHeight: '70vh', overflow: 'auto'}}
        onCancel={onCancel}
        { ...formProps }
      >
        <Form>
          {
            radioValue === 'OFFLINE_PAYMENT' && (
              <Alert
                message={messages('finance-4.key190')/*线下支付，确认付款后，支付状态直接变为支付成功*/}
                type="info"
                showIcon
                style={{ position: 'relative', top: -10 }}
              />
            )
          }
          <div style={{ marginBottom: 15 }}>01. {messages('finance-4.key191')/*选择付款账号*/}</div>
          {
            radioValue === 'WAIT_CHECK' ? (
              <Form.Item  {...formItemLayout} label={messages('finance-4.key192')/*付款账户*/} style={{ marginBottom: accountBalance ? '16px' : '32px' }}>
                {getFieldDecorator('payCompanyBankNumber', {
                  rules: [{
                    required: true, message: messages('finance-4.key136')/*请选择temp*/
                  }]
                })(
                  <Selector
                    selectorItem={{
                      url: `/api/companyBankAuth/getAuthCompanyBank/${loginUser.userOID}`,
                      label: item => item.companyBank.bankAccountName,
                      key: item => item.companyBank.bankAccountNumber,
                      showSearchLabel: item => (
                        <div>
                          {`${item.companyBank.bankAccountName} - ${item.companyBank.bankAccountNumber}`}
                          {item.bankPayInfo && item.bankPayInfo.status === 'Y' && item.accountType !== 'ALIPAY_LOGON_ID' && (
                            <span style={{color: "#108ee9"}}>{messages('finance-4.key193')/*（银企直联生效中）*/}</span>
                          )}
                        </div>
                      ),
                      dynamicUrl: true
                    }}
                    params={{
                      setOfBooksId: record[0] ? record[0].setOfBooksId : '',
                      paymentMethodCode: record[0] ? record[0].paymentMethodCategory : '',
                      currency: record[0] ? record[0].currency : '',
                      companyId
                    }}
                    entity
                    disabled={companyCombinedPayment}
                    onChange={this.handleBanKChange}
                  />
                )}
              </Form.Item>
            ) : (
              <Form.Item  {...formItemLayout} label={messages('finance-4.key192')/*付款账户*/} style={{ marginBottom: accountBalance ? '16px' : '32px' }}>
                {getFieldDecorator('payCompanyBankNumber', {
                  rules: [{
                    required: !this.props.bankInfo, message: messages('finance-4.key136')/*请选择temp*/
                  }]
                })(
                  <div>
                    {
                      Object.keys(bankInfo).length > 0 && (
                        <span>
                          {`${bankInfo.companyBank.bankAccountName} - ${bankInfo.companyBank.bankAccountNumber}`}
                          {bankInfo.bankPayInfo && bankInfo.bankPayInfo.status === 'Y' && bankInfo.accountType !== 'ALIPAY_LOGON_ID' && (
                            <span style={{color: "#108ee9"}}>{messages('finance-4.key193')/*（银企直联生效中）*/}</span>
                          )}
                        </span>
                      )
                    }
                  </div>
                )}
              </Form.Item>
            )
          }
          {
            accountBalance && (
              <Row style={{ marginBottom: '16px' }}>
                <Col span={6} style={{ textAlign: 'right', color: '#1e2126' }}>{messages('finance-4.key194')/*账户余额：*/}</Col>
                <Col span={14} offset={1}>
                  {bankInfo.companyBank.currencyCode}
                  <span style={{ marginLeft: '10px' }}>
                    {
                      surplusLoading ? <Spin/> : (
                        typeof surplus === 'number' ? this.filterMoney(surplus,queryCurrencyPrecision(bankInfo.companyBank.currencyCode)) :
                          <a onClick={this.getSurplus}>{messages('finance-4.key54')/*查询余额*/}</a>
                      )
                    }
                  </span>
                </Col>
              </Row>
            )
          }
          {radioValue === 'EBANK_PAYMENT' && (
            <Form.Item  {...formItemLayout} label={messages('finance-4.key195')/*报盘文件格式*/}>
              {getFieldDecorator('templateId')(
                <Select>
                  {optionList.map(item => <Option key={item.id}>{item.templateName}</Option>)}
                </Select>
              )}
            </Form.Item>
          )}
          <Form.Item  {...formItemLayout} label={messages('common.currency')/*币种*/}>
            {getFieldDecorator('currency', {
              rules: [{ required: true }],
              initialValue: record[0] ? record[0].currency : undefined
            })(
              <Input disabled/>
            )}
          </Form.Item>
          <Form.Item  {...formItemLayout} label={messages('common.currency.rate')/*汇率*/}>
            {getFieldDecorator('exchangeRate', {
              rules: [{ required: true }],
              initialValue: rate
            })(
              <Input disabled/>
            )}
          </Form.Item>
          <div style={{ marginBottom: 15 }}>02. {messages('finance-4.key196')/*选择付款方式*/}</div>
          <Form.Item  {...formItemLayout} label={messages('finance-4.key81')/*付款方式*/}>
            {getFieldDecorator('paymentTypeId', {
              rules: [{ required: true, message: messages('finance-4.key136')/*请选择temp*/ }]
            })(
              <Selector
                selectorItem={{
                  url: '/api/comapnyBankPayment/get/company/bank/payment/by/bank/account/number',
                  key: 'paymentMethodId',
                  label: 'description',
                  dynamicUrl: true
                }}
                params={{
                  number: bankInfo.companyBank ? bankInfo.companyBank.bankAccountNumber : '',
                  paymentMethod: radioValue === 'WAIT_CHECK' ? 'ONLINE_PAYMENT' : radioValue,
                  accountType: bankInfo.accountType
                }}
                entity
                firstOptionToValue
                onChange={this.handleChangeType}
                onRef={ref => this.selectorRef = ref}
                disabled={selectFlag}
              />
            )}
          </Form.Item>
          {
            chequeNumberFlag.paymentMethodCode === 'PAY_IN_CHEQUE' && (
              <Form.Item  {...formItemLayout} label={messages('finance-4.key197')/*支票号*/}>
                {getFieldDecorator('chequeNumber')(
                  <Input placeholder={messages('finance-4.key70')/*请输入temp2*/}/>
                )}
              </Form.Item>
            )
          }
          <Form.Item {...formItemLayout} label={messages('finance-4.key63')/*备注temp*/}>
            {getFieldDecorator('remark')(
              <Input.TextArea
                autosize={{ minRows: 2 }}
                style={{ minWidth: '100%' }}
                placeholder={messages('finance-4.key70')/*请输入temp2*/}
              />
            )}
          </Form.Item>
          {
            radioValue === 'OFFLINE_PAYMENT' && (
              <div>
                <div style={{ marginBottom: 15 }}>03. {messages('finance-4.key198')/*选择付款日期*/}</div>
                <Form.Item  {...formItemLayout} label={messages('finance-4.key199')/*付款日期*/}>
                  {getFieldDecorator('payDate', {
                    rules: [{ required: true, message: messages('finance-4.key136')/*请选择temp*/ }],
                    initialValue: moment(new Date())
                  })(
                    <DatePicker disabledDate={current => current && current.valueOf() > Date.now()}/>
                  )}
                </Form.Item>
              </div>
            )
          }
          {
            radioValue === 'EBANK_PAYMENT' && (
              <div>
                <div style={{ marginBottom: 15 }}>03. {messages('finance-4.key200')/*点击下方【导出报盘文件/明细】按钮*/}</div>
                <div>
                  <Row>
                    <Col offset={1} span={23}>1.{messages('finance-4.key201')/*导出报盘文件/明细后，单据状态变为【支付中】*/}</Col>
                  </Row>
                  <Row>
                    <Col offset={1} span={23}>2.{messages('finance-4.key202')/*可通过报盘文件/明细，在网银中进行支付*/}</Col>
                  </Row>
                  <Row>
                    <Col offset={1} span={23}>3.{messages('finance-4.key203')/*支付成功后，在【支付中】标签下确认支付状态*/}</Col>
                  </Row>
                  <Row>
                    <Col offset={1} span={23}>4.{messages('finance-4.key204')/*使用对应银行报盘文件格式，导出文件可以直接在网银支付中使用，通用模版则需要根据对应银行的要求导出后进行调整*/}</Col>
                  </Row>
                </div>
              </div>
            )
          }
          <ExportModal
            exportTitle={''}
            exportType="REIMBURSEMENT_BATCH"
            exportCondition={{ reimbursementBatchOID, templateId: getFieldValue('templateId') }}
            wrappedComponentRef={(inst) => this.export = inst}
            exportCommand={storageKey === 'file' ? 'BATCH' : 'BATCH_DETAIL'}
          />
          <ErrorModal
            visible={errorVisible}
            close={this.handleCloseError}
            data={errorData}
            isPayCheck={isPayCheck}
            bankInfo={bankInfo}
            mode={mode}
            params={continueParams}
            radioValue={radioValue}
            storageKey={storageKey}
          />
        </Form>
      </Modal>
    )
  }

  static propTypes = {
    radioValue: PropTypes.string,
    visible: PropTypes.bool,
    onCancel: PropTypes.func,
    record: PropTypes.array,
    companyId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    onOk: PropTypes.func,
    mode: PropTypes.string
  }

}

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser,
    company: state.login.company
  }
}

const HocPayModal = CheckModal(PayModal);
const WrappedPayModal = Form.create()(HocPayModal);
export default connect(mapStateToProps)(WrappedPayModal)
